package com.estrend.redbird.utils

import android.content.Context
import android.os.Build
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import java.util.UUID


object DeviceUtils {
    private const val PREF_UNIQUE_ID = "PREF_UNIQUE_ID"
    private const val UNIQUE_ID_KEY = "UNIQUE_ID"

    fun getDeviceUniqueId(context: Context): String {
        val sharedPrefs = context.getSharedPreferences(PREF_UNIQUE_ID, Context.MODE_PRIVATE)
        var uniqueId = sharedPrefs.getString(UNIQUE_ID_KEY, null)

        if (uniqueId == null) {
            val androidId = getAndroidId(context)
            uniqueId = if (!androidId.isNullOrEmpty()) {
                androidId
            } else {
                UUID.randomUUID().toString()
            }
            with(sharedPrefs.edit()) {
                putString(UNIQUE_ID_KEY, uniqueId)
                apply()
            }
        }

        return uniqueId
    }

    private fun getAndroidId(context: Context): String? {
        return try {
            Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
        } catch (e: Exception) {
            Log.e("getAndroidId", "Exception occurred while getting ANDROID_ID", e)
            null
        }
    }

    fun getDeviceModel(): String {
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        return if (model.startsWith(manufacturer)) {
            capitalize(model)
        } else {
            capitalize(manufacturer) + " " + model
        }
    }

    private fun capitalize(s: String?): String {
        if (s == null || s.length == 0) {
            return ""
        }
        val chars = s.toCharArray()
        chars[0] = chars[0].uppercaseChar()
        return String(chars)
    }

    fun getDeviceName():String{

       return Build.MODEL
    }

    fun getSDKVersion():String{
        return android.os.Build.VERSION.SDK_INT.toString()
    }
    fun getAndroidVersion(): String {
        return Build.VERSION.RELEASE
    }

    fun getManufacturer(): String {
        return Build.MANUFACTURER;
    }

    fun getHiegtWidth(mContext: Context):String{

        val dm = DisplayMetrics()
        val windowManager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(dm)
        return dm.widthPixels.toString()+"x"+dm.heightPixels.toString()
    }

    fun getScreenSizeInInches(context: Context): Double {
        val dm = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager?.defaultDisplay?.getMetrics(dm)
        val widthInches = dm.widthPixels / dm.xdpi.toDouble()
        val heightInches = dm.heightPixels / dm.ydpi.toDouble()
        return Math.sqrt(Math.pow(widthInches, 2.0) + Math.pow(heightInches, 2.0))
    }





}